<template>
	<view class="uni-submit-order bottom-index">
		<!-- #ifdef MP-WEIXIN -->
		<qmy-custom-navbar :title="'提交订单'"></qmy-custom-navbar>
		<!-- #endif -->
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
		<!-- 主要内容区域 -->
		<view class="content" :style="{paddingTop:menuObject.top + menuObject.height +20 + 'px'}">
			<!-- 订单进度指示器 -->
			<view class="order-progress">
				<view class="progress-item">
					<view class="progress-icon active">1</view>
					<text class="progress-text active">确认订单</text>
				</view>
				<view class="progress-line">
					<view class="line"></view>
				</view>
				<view class="progress-item">
					<view class="progress-icon">2</view>
					<text class="progress-text">支付订单</text>
				</view>
				<view class="progress-line">
					<view class="line"></view>
				</view>
				<view class="progress-item">
					<view class="progress-icon">3</view>
					<text class="progress-text">完成订单</text>
				</view>
			</view>

			<!-- 收货地址区域 -->
			<view class="address-section" @click="chooseAddress">
				<view v-if="!addressInfo" class="no-address">
					<text class="iconfont ic-weizhi fs-50 col-00ba31"></text>
					<text class="tip-text">添加收货地址</text>
					<text class="iconfont ic-you fs-32"></text>
				</view>
				<view v-else class="address-info">
					<view>
						<view class="user-info">
							<text class="name">{{addressInfo.name}}</text>
							<text class="mobile">{{addressInfo.mobile}}</text>
							<text class="default-tag" v-if="addressInfo.is_default">默认</text>
						</view>
						<view class="address-detail">
							<text class="address-text">{{addressInfo.formatted_address}}{{addressInfo.address}}</text>
						</view>
					</view>
					<text class="iconfont ic-you fs-32 arrow"></text>
				</view>
			</view>

			<!-- 商品列表 -->
			<view class="goods-section">
				<view class="section-header">
					<view class="shop-info">
						<image class="shop-icon" src="/static/logo.png" mode="aspectFit"></image>
						<text class="shop-name">奇妙野商城</text>
					</view>
					<view class="delivery-status" v-if="deliveryInfo.status">
						<text class="status-text">{{deliveryInfo.statusText}}</text>
					</view>
				</view>
				<view class="goods-list">
					<view class="goods-item" v-for="(item, index) in orderGoods" :key="index">
						<image class="goods-image" @click="$previewImage(item.image,0)" :src="item.image"
							mode="aspectFill"></image>
						<view class="goods-info">
							<view class="goods-name">{{item.name}}</view>
							<view class="goods-specs">
								<text class="spec-badge" v-for="(spec, sIndex) in item.specs"
									:key="sIndex">{{spec}}</text>
							</view>
							<view class="goods-price-qty">
								<text class="price">¥{{(item.price/100).toFixed(2)}}</text>
								<text class="qty-num">×{{item.quantity}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="goods-summary">
					<text class="total-qty">共 {{getTotalQuantity()}} 件商品</text>
					<text class="total-price">小计: ¥{{(totalGoodsPrice/100).toFixed(2)}}</text>
				</view>
			</view>

			<!-- 配送、支付、备注等信息 -->
			<view class="order-info-section">
				<view class="info-item">
					<text class="info-label">配送方式</text>
					<view class="info-value">
						<text>快递配送</text>
					</view>
				</view>
				<view class="info-item">
					<text class="info-label">发票信息</text>
					<view class="info-value">
						<text>如需开票请联系客服</text>
					</view>
				</view>
				<view class="info-item remark-item">
					<text class="info-label">订单备注</text>
					<input type="text" class="text-ali-r fs-28" v-model="remark" confirm-type="done"
						placeholder="选填，限20字以内" :maxlength="20" />
				</view>
			</view>

			<!-- 价格明细 -->
			<view class="price-section">
				<view class="price-item">
					<text class="price-label">商品金额</text>
					<text class="price-value">¥{{(totalGoodsPrice/100).toFixed(2)}}</text>
				</view>
				<view class="price-item">
					<text class="price-label">运费</text>
					<text class="price-value" v-if="deliveryFee > 0">¥{{(deliveryFee/100).toFixed(2)}}</text>
					<text class="price-value free-delivery" v-else>包邮</text>
				</view>
				<view class="divider"></view>
				<view class="price-item total">
					<text class="price-label">实付款</text>
					<text class="price-value total-value">¥{{(totalPayPrice/100).toFixed(2)}}</text>
				</view>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="footer bottom-h">
			<view class="total-section">
				<view class="total-price">
					<text class="label">合计：</text>
					<text class="value">¥{{(totalPayPrice/100).toFixed(2)}}</text>
				</view>
			</view>
			<view class="submit-btn" @click="submitOrder">提交订单</view>
		</view>
	</view>
</template>

<script>
	import {
		store
	} from '@/utils/store.js';

	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				dataLoaded: false, // 数据加载状态
				addressInfo: null, // 收货地址信息
				orderGoods: [], // 订单商品列表
				remark: '', // 订单备注
				totalGoodsPrice: 0, // 商品总金额（单位：分）
				deliveryFee: 0, // 运费（单位：分）
				cartItemIds: [], // 来自购物车的ID列表
				userBalance: 0, // 用户余额（单位：分）
				fromType: 'cart', // 来源类型：cart-购物车，buy-立即购买
				skuInfo: null, // 立即购买时的SKU信息
				deliveryInfo: {
					status: false,
					statusText: ''
				}
			}
		},
		computed: {
			// 用户信息
			userInfo() {
				return store.userInfo;
			},
			// 实付金额
			totalPayPrice() {
				// 确保是整数
				return Math.round(Number(this.totalGoodsPrice) + Number(this.deliveryFee));
			}
		},
		onLoad(options) {
			// 解析传递的参数
			if (options.type === 'buy' || options.type === 'buyNow') {
				// 从商品详情页直接购买
				this.fromType = 'buy';
				if (options.skuInfo) {
					try {
						const skuInfo = JSON.parse(decodeURIComponent(options.skuInfo));
						this.skuInfo = skuInfo;
						this.loadDirectBuyData(skuInfo);
					} catch (e) {
						this.$Toast('商品信息解析失败');
					}
				} else {
					this.$Toast('商品信息不完整');
				}
			} else {
				// 从购物车进入
				this.fromType = 'cart';
				if (options.cartItemIds) {
					try {
						this.cartItemIds = JSON.parse(decodeURIComponent(options.cartItemIds));
						this.loadCartData(this.cartItemIds);
					} catch (e) {
						this.$Toast('商品信息解析失败');
					}
				} else {
					this.$Toast('商品信息不完整');
				}
			}
			// 获取用户地址
			this.loadUserAddress();
		},
		methods: {
			// 加载直接购买的商品数据
			loadDirectBuyData(skuInfo) {
				if (!skuInfo) {
					return;
				}
				try {
					const item = {
						goods_id: skuInfo.goods_id,
						sku_id: skuInfo.sku_id,
						name: skuInfo.goods_name || skuInfo.name,
						image: skuInfo.image,
						specs: skuInfo.specs || [],
						price: skuInfo.price,
						quantity: skuInfo.quantity || 1,
						stock: skuInfo.stock,
						free_shipping: skuInfo.free_shipping || false,
						shipping_fee: skuInfo.shipping_fee || 0
					};
					this.orderGoods = [item];
					this.calculateGoodsPrice();
					this.calculateDeliveryFee();

				} catch (e) {
					this.$Toast('商品数据处理失败');
				}
			},

			// 加载购物车中选中的商品数据
			loadCartData(cartItemIds) {
				if (cartItemIds && cartItemIds.length > 0) {
					// 调用接口获取购物车中选择的商品数据
					this.$Route('get-private-data', !this.dataLoaded).getUserCartInfo(cartItemIds).then(res => {
						this.dataLoaded = true;
						if (res.data.items && res.data.items.length > 0) {
							// 处理返回的数据
							this.orderGoods = res.data.items.map(item => ({
								goods_id: item.goods_id,
								sku_id: item.sku_id,
								name: item.goods_name || item.name,
								image: item.goods_image,
								specs: item.specs || [],
								price: item.price,
								quantity: item.quantity || 1,
								free_shipping: item.free_shipping || false,
								shipping_fee: item.shipping_fee || 0
							}));
							if (res.data.total_price) {
								this.totalGoodsPrice = res.data.total_price;
							} else {
								// 计算商品总价
								this.calculateGoodsPrice();
							}
							// 计算运费
							this.calculateDeliveryFee();
						} else {
							this.$Toast('购物车为空');
							setTimeout(() => {
								this.$NavigateBack();
							}, 1000);
						}
					}).catch(err => {
						this.dataLoaded = true;
						console.error('遇到错误:', err); // 打印错误信息
						let {
							code,
							msg
						} = this.$parseError(err); // 调用公共解析方法
						this.$Toast(msg);
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
							}
						}, 1600);
					});
				} else {
					this.dataLoaded = true;
				}
			},

			// 计算商品总价
			calculateGoodsPrice() {
				// 确保orderGoods为数组并且有值
				if (!Array.isArray(this.orderGoods) || this.orderGoods.length === 0) {
					this.totalGoodsPrice = 0;
					return;
				}

				this.totalGoodsPrice = this.orderGoods.reduce((total, item) => {
					// 确保价格和数量为数字
					const price = Number(item.price) || 0;
					const quantity = Number(item.quantity) || 0;
					return total + (price * quantity);
				}, 0);
				
				// 确保总价是整数
				this.totalGoodsPrice = Math.round(this.totalGoodsPrice);
			},

			// 计算运费
			calculateDeliveryFee() {
				// 设置基础运费
				let baseFee = 0; // 基础运费0元

				// 检查商品是否都包邮
				let allFreeShipping = true;
				let maxShippingFee = 0;

				// 遍历商品检查运费情况
				this.orderGoods.forEach(item => {
					if (!item.free_shipping) {
						allFreeShipping = false;
						// 如果商品有自定义运费且高于当前最高运费，则更新最高运费
						if (item.shipping_fee && item.shipping_fee > maxShippingFee) {
							maxShippingFee = item.shipping_fee;
						}
					}
				});

				// 如果所有商品都包邮，则运费为0
				if (allFreeShipping) {
					this.deliveryFee = 0;
					return;
				}

				// 如果有自定义运费的商品，使用最高运费值
				if (maxShippingFee > 0) {
					this.deliveryFee = maxShippingFee;
				} else {
					this.deliveryFee = baseFee;
				}
				
				// 确保运费是整数
				this.deliveryFee = Math.round(this.deliveryFee);
			},

			// 加载用户收货地址
			loadUserAddress() {
				// 获取默认地址或最近使用的地址
				this.$Route('get-private-data', !this.dataLoaded).getUserAddressList().then(res => {
					if (res.data && Array.isArray(res.data) && res.data.length > 0) {
						// 使用第一个地址
						this.addressInfo = res.data[0];
					}
					if (this.fromType == 'buy') {
						this.dataLoaded = true;
					}
				}).catch(err => {
					if (this.fromType == 'buy') {
						this.dataLoaded = true;
					}
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			},

			// 选择收货地址
			chooseAddress() {
				uni.navigateTo({
					url: '/qmy_user/user/address/list?from=order',
					events: {
						// 也处理refreshData事件，以确保兼容性
						refreshData: (address) => {
							if (address) {
								this.addressInfo = address;
								console.log('地址数据已刷新:', address);
							}
						}
					}
				});
			},

			// 提交订单
			submitOrder() {
				// 节流
				this.$debounce(() => {
					// 检查是否选择了收货地址
					if (!this.addressInfo) {
						return this.$Toast('请选择收货地址');
					}
					
					// 确保所有金额都是整数
					const totalFee = Math.round(this.totalPayPrice);
					const goodsPrice = Math.round(this.totalGoodsPrice);
					const deliveryFee = Math.round(this.deliveryFee);
					
					// 组装订单数据
					const orderData = {
						address_id: this.addressInfo._id, // 收货地址id
						goods_list: this.orderGoods, // 商品列表
						total_fee: totalFee, // 总金额
						goods_price: goodsPrice, // 商品价格
						delivery_fee: deliveryFee, // 配送费
						remark: this.remark, // 备注
						from_cart: this.fromType === 'cart', // 是否从购物车下单
						cart_item_ids: this.fromType === 'cart' ? this.cartItemIds : [] // 购物车商品id
					};

					// 调用接口提交订单
					this.$Route('add-private-data').createGoodsOrder(orderData).then(res => {
						// 订单创建成功，跳转支付收银台页
						let options = {
							order_no: res.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
							out_trade_no: res.plugin_order_no, // 插件支付单号
							type: 'goods', // 订单类型
							description: `奇妙野商城订单-${res.plugin_order_no}`, // 支付描述
							total_fee: totalFee, // 支付金额，单位分 100 = 1元
						};
						let optionsStr = encodeURI(JSON.stringify(options));
						this.$NavigateTo(`/pages/detail/pay-desk?options=${optionsStr}`);
					}).catch(err => {
						console.error('遇到错误:', err); // 打印错误信息
						let {
							code,
							msg
						} = this.$parseError(err); // 调用公共解析方法
						this.$Toast(msg);
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
							}
						}, 1600);
					});
				}, 1000, true, "submitOrder")
			},

			// 获取总商品数量
			getTotalQuantity() {
				if (!Array.isArray(this.orderGoods) || this.orderGoods.length === 0) {
					return 0;
				}
				return this.orderGoods.reduce((total, item) => {
					return total + Number(item.quantity || 0);
				}, 0);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uni-submit-order {
		min-height: 100vh;
		background-color: #f5f7fa;
		position: relative;
	}

	.content {
		padding: 20rpx;
	}

	/* 订单进度指示器 */
	.order-progress {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.progress-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: relative;

			.progress-icon {
				width: 60rpx;
				height: 60rpx;
				background-color: #e0e0e0;
				color: #999;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
				font-weight: bold;
				margin-bottom: 10rpx;

				&.active {
					background-color: #14cc60;
					color: #ffffff;
				}
			}

			.progress-text {
				font-size: 24rpx;
				color: #999;

				&.active {
					color: #14cc60;
					font-weight: bold;
				}
			}
		}

		.progress-line {
			flex: 1;
			height: 60rpx;
			position: relative;
			z-index: 1;
			display: flex;
			align-items: center;

			.line {
				width: 100%;
				height: 2rpx;
				background-color: #e0e0e0;
			}
		}
	}

	/* 收货地址部分 */
	.address-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		position: relative;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.no-address {
			display: flex;
			align-items: center;
			height: 120rpx;

			.iconfont {
				margin-right: 20rpx;
			}

			.tip-text {
				flex: 1;
				font-size: 30rpx;
				color: #333;
			}
		}

		.address-info {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;

			.user-info {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				.name {
					font-size: 32rpx;
					font-weight: 600;
					margin-right: 20rpx;
				}

				.mobile {
					font-size: 28rpx;
					color: #666;
					margin-right: 20rpx;
				}

				.default-tag {
					font-size: 20rpx;
					color: #ffffff;
					background-color: #14cc60;
					padding: 2rpx 10rpx;
					border-radius: 6rpx;
				}
			}

			.address-detail {
				display: flex;
				align-items: flex-start;

				.iconfont {
					color: #14cc60;
					margin-right: 10rpx;
					flex-shrink: 0;
					margin-top: 4rpx;
				}

				.address-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.4;
				}
			}

			.arrow {
				margin-left: 10rpx;
			}
		}
	}

	/* 商品列表部分 */
	.goods-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.section-header {
			padding: 20rpx 30rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.shop-info {
				display: flex;
				align-items: center;

				.shop-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}

				.shop-name {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
				}
			}

			.delivery-status {
				margin-left: auto;
				padding: 0 20rpx;
				border-left: 1rpx solid #f5f5f5;

				.status-text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}

		.goods-list {
			.goods-item {
				display: flex;
				padding: 30rpx;
				border-bottom: 1rpx solid #f5f5f5;

				&:last-child {
					border-bottom: none;
				}

				.goods-image {
					width: 170rpx;
					height: 170rpx;
					border-radius: 8rpx;
					background-color: #f7f7f7;
					margin-right: 20rpx;
					flex-shrink: 0;
				}

				.goods-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.goods-name {
						font-size: 28rpx;
						color: #333;
						line-height: 1.4;
						margin-bottom: 10rpx;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}

					.goods-specs {
						font-size: 24rpx;
						color: #999;
						margin-bottom: 16rpx;

						.spec-badge {
							display: inline-block;
							background-color: #f5f5f5;
							padding: 2rpx 10rpx;
							margin-right: 10rpx;
							border-radius: 4rpx;
						}
					}

					.goods-price-qty {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.price {
							font-size: 30rpx;
							color: #FF3B30;
							font-weight: 600;
						}

						.qty-num {
							font-size: 28rpx;
							color: #666;
							margin-left: 10rpx;
						}
					}
				}
			}
		}

		.goods-summary {
			padding: 30rpx;
			border-top: 1rpx solid #f5f5f5;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.total-qty {
				font-size: 26rpx;
				color: #666;
			}

			.total-price {
				font-size: 30rpx;
				color: #FF3B30;
				font-weight: 600;
			}
		}
	}

	/* 配送、支付、备注等信息 */
	.order-info-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.info-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.info-label {
				font-size: 28rpx;
				color: #333;
				width: 160rpx;
			}

			.info-value {
				flex: 1;
				font-size: 28rpx;
				color: #666;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}

			&.remark-item {
				align-items: flex-start !important;
			}
		}
	}

	/* 价格明细部分 */
	.price-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.price-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.price-label {
				font-size: 28rpx;
				color: #666;
			}

			.price-value {
				font-size: 28rpx;
				color: #333;
			}
		}

		.divider {
			height: 1rpx;
			background-color: #f5f5f5;
			margin: 20rpx 0;
		}

		.total {
			margin-top: 10rpx;
			margin-bottom: 10rpx;

			.price-label {
				font-size: 30rpx;
				color: #333;
				font-weight: 600;
			}

			.total-value {
				font-size: 32rpx;
				color: #FF3B30;
				font-weight: 600;
			}
		}
	}

	/* 底部部分 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 100;

		.total-section {
			flex: 1;
			padding-left: 30rpx;

			.total-price {
				display: flex;
				align-items: baseline;

				.label {
					font-size: 28rpx;
					color: #333;
				}

				.value {
					font-size: 36rpx;
					color: #FF3B30;
					font-weight: 600;
				}
			}
		}

		.submit-btn {
			width: 240rpx;
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			background-color: #14cc60;
			color: #ffffff;
			font-size: 32rpx;
			font-weight: 600;

			&:active {
				background-color: #11b051;
			}
		}
	}

	/* 添加包邮样式 */
	.free-delivery {
		color: #14cc60 !important;
	}
</style>